package com.lagou.encoder;

import com.alibaba.fastjson.JSON;
import com.lagou.proto.RpcRequest;
import com.lagou.proto.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


public class NettyClientEncoder extends MessageToByteEncoder<RpcRequest> {


    protected void encode(ChannelHandlerContext channelHandlerContext, RpcRequest rpcRequest, ByteBuf out) throws Exception {
        try {
            byte[] requestBytes = JSON.toJSONBytes(rpcRequest);
            //请求内容长度
            out.writeInt(requestBytes.length);
            //请求内容
            out.writeBytes(requestBytes);

        } catch (Exception e) {
            e.printStackTrace();
            channelHandlerContext.channel().close();
        }
    }

}
